﻿using DMSystem_Sqlite_WebAPI.Modals;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;

namespace DMSystem_Sqlite_WebAPI.Filters
{
    public class GlobalResponseWrapperFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            // 在控制器方法执行前不处理
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Result is ObjectResult objectResult)
            {
                // 如果已经是 ApiResponse 就不再包装
                if (objectResult.Value is ApiResponse)
                    return;

                // 如果 StatusCode 是 400/500 等错误码，则统一封装为 Fail
                if (objectResult.StatusCode >= 400)
                {
                    context.Result = new ObjectResult(ApiResponse.Fail("请求失败", objectResult.Value))
                    {
                        StatusCode = 200
                    };
                }
                else
                {
                    context.Result = new ObjectResult(ApiResponse.Success(objectResult.Value))
                    {
                        StatusCode = objectResult.StatusCode
                    };
                }
            }
        }
    }
}
